package com.heshida.controller;

import com.heshida.po.IdWorker;
import com.heshida.po.Result;
import com.heshida.service.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private AliPayService aliPayService;

    //下订单
    @RequestMapping("/createNative")
    public Map createNative(String total_fee){
        IdWorker idWorker = new IdWorker();
        long nextId = idWorker.nextId();
        System.out.println(nextId);
        return aliPayService.createNative(nextId+"",total_fee);
    }

    @RequestMapping("/queryPayStatus")
    public Result queryPayStatus(String out_trade_no){
        Result result=null;
        int x=0;
        while(true){
            Map<String,String> map=null;
            map= aliPayService.queryPayStatus(out_trade_no);
            if(map==null){
                result=new Result(false,"支付出错了");
                break;
            }

            if(map.get("tradestatus")!=null &&map.get("tradestatus").equals("TRADE_SUCCESS")){
                result=new Result(true,"支付成功");

                //向数据库增加支付记录

                break;
            }
            if(map.get("tradestatus")!=null &&map.get("tradestatus").equals("TRADE_CLOSED")){
                result=new Result(true,"未付款交易超时，或支付完成全额退款");
                break;
            }
            if(map.get("tradestatus")!=null &&map.get("tradestatus").equals("TRADE_FINISHED")){
                result=new Result(true,"交易结束，不可退款");
                break;
            }
            if(map.get("tradestatus")!=null &&map.get("tradestatus").equals("WAIT_BUYER_PAY")){
                result=new Result(false,"下单成功，等待支付");

            }
            try {
                Thread.sleep(3000);//间隔1秒查询订单状态
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(result);
            x++;
            if(x>=20){
                result=new Result(false,"二维码超时");
                break;
            }
        }

        return result;
    }


}
